﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using FluentValidation;
using FluentValidation.Results;
using PDX;

namespace PdxDemo.FluentValidationDemo
{
    public class FluentValidationModel : INPC
    {
        PDX.IPropertyModel propertyModel;
        FluentValidationResult result;

        public FluentValidationModel(PDX.IPropertyModel propertyModel, FluentValidationResult result)
        {
            this.propertyModel = propertyModel;
            this.result = result;

            result.PropertyChanged += new PropertyChangedEventHandler(result_PropertyChanged);

            ReEvaluate();
        }

        void result_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            ReEvaluate();
        }

        void ReEvaluate()
        {
            if (result.Result.IsValid)
            {
                Message = string.Empty;
                return;
            }

            foreach (var error in result.Result.Errors)
            {
                if (error.PropertyName == propertyModel.Resolution.Property.Name)
                {
                    Message = error.ErrorMessage;
                    return;
                }
            }

            Message = string.Empty;
            return;
        }


        public bool HasMessage
        {
            get
            {
                return !string.IsNullOrEmpty(Message);
            }
        }


        string message = string.Empty;
        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                if (message != value)
                {
                    message = value;
                    OnPropertyChanged("Message");
                    OnPropertyChanged("HasMessage");
                }
            }
        }
    }
}
